package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
      MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConstantProperties.getEndpointUrl())
                .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                .build();

        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if(!exists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        }

        //上传到minio
        String uploadFilename = file.getOriginalFilename();
        InputStream fis = file.getInputStream();
        String filename =new DateTime().toString("/yyyy-MM/dd/")
                + System.currentTimeMillis()+"_"
                + UUID.randomUUID().toString().substring(0,6)
                +  uploadFilename.substring(uploadFilename.lastIndexOf("."));
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .stream(fis , fis.available() , -1)
                .object(filename)
                .build()
        );

        //返回图片路径回显
        String filePath = minioConstantProperties.getEndpointUrl()
                +"/" + minioConstantProperties.getBucketName()
                +"/" + filename;
        return Result.ok(filePath);

    }
}
